package com.lms.netty.tcp.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-16 10:36
 * @Description:
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    /**
     * @Author 李孟帅
     * @Description 当通道就绪就会触发该方法
     * @Date 2020/6/16
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg="hello";
        byte[] bytes = msg.getBytes("UTF-8");
        for (int i = 0; i < 10; i++) {
            System.out.println("客户端发送数据");
            MessageProtocol message = new MessageProtocol();
            message.setContent(bytes);
            message.setLen(bytes.length);
            ctx.writeAndFlush(message);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接受的数据:");
        System.out.println("长度："+len);
        System.out.println("内容："+new String(content, CharsetUtil.UTF_8));
        System.out.println("客户端收到的数据包个数："+(++count));
        System.out.println();
    }
}
